﻿using Oplaco.Samples.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;

namespace Oplaco.Samples.WebApi.Formatters
{
    public class UploadMultipartMediaTypeBufferedFormatter : BufferedMediaTypeFormatter    
    {
        private static Type _supportedType = typeof(FileItem);

        public UploadMultipartMediaTypeBufferedFormatter()
        {
            // Add the supported media type.
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/jpeg"));
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/jpg"));
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/png"));
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));
        }

        public override bool CanReadType(Type type)
        {
            return (type == _supportedType);
        }

        public override bool CanWriteType(Type type)
        {
            return (type == _supportedType);
        }

        public override object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)        
        {
            var taskSource = new TaskCompletionSource<object>();
            try
            {
                byte[] fileBytes = new byte[readStream.Length];
                readStream.Read(fileBytes, 0, (int)fileBytes.Length);
                return (object)new System.Data.Linq.Binary(fileBytes);
            }
            catch (Exception e)
            {
                taskSource.SetException(e);
            }
            return null;
        }

        public virtual void WriteToStream(Type type, object value, Stream writeStream, HttpContent content) { 
            
        }
    }
}